﻿using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace CoderbitsWinRTAPI
{
    public class APIClient
    {
        const string PATH = "https://coderbits.com/";

        /// <summary>
        /// Synchronously get the coderbits profile of a specified user
        /// </summary>
        /// <param name="username">Account name</param>
        /// <returns></returns>
        public Profile GetProfile(string username)
        {
            return GetProfileAsync(username).Result;
        }

        /// <summary>
        /// Asynchronously get the coderbits profile of a specified user
        /// </summary>
        /// <param name="username">Account name</param>
        /// <returns></returns>
        public async Task<Profile> GetProfileAsync(string username)
        {
            Profile coderbitsProfile = new Profile();

            // Create HttpClient for making request for profile
            var client = new HttpClient();

            // Get profile response as a JSON string
            HttpResponseMessage response = await client.GetAsync(PATH + username + ".json");
            if (response.StatusCode == HttpStatusCode.OK)
            {
                string responseString = await response.Content.ReadAsStringAsync();

                // Convert to Coderbits profile
                coderbitsProfile = await JsonConvert.DeserializeObjectAsync<Profile>(responseString);
            }
            else
            {
                throw new Exception(response.StatusCode.ToString() + " " + response.ReasonPhrase);
            }

            //Return the profile
            return coderbitsProfile;
        }
    }
}
